//
//  HEHealthCheckDataController.m
//  HealthFamily
//
//  Created by LOOK on 2020/12/20.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthCheckDataController.h"
#import "MJCSegmentInterface.h"
#import "HEHealthCheckChartController.h"

@interface HEHealthCheckDataController ()

@property(nonatomic, strong) QMUIPopupMenuView *popUsersView;
@property(nonatomic, strong) UILabel *nameLb;
@property(nonatomic, strong) NSMutableArray *vcs;
@end

@implementation HEHealthCheckDataController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"健康数据";
    
    [self getBindUserData];
    [self setNav];
    [self setupData];
    
    [self initTitleView];
    [self initUI];
}

- (void)setNav {
    self.zx_navBar.backgroundColor = KHexColor(@"#3E8BF8");
    self.zx_backBtnImageName = @"back_icon";
    self.zx_navLineView.hidden = YES;
    self.zx_navTintColor = KWhiteColor;
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleLight;
}

- (void)initTitleView {
    // 标题栏
    UIView *titleView = [UIView new];
    
    UILabel *nameLb = [UILabel new];
    nameLb.text = [NSString stringWithFormat:@"健康管理(%@)", _selectUser.realname];
    nameLb.font = DYFont(17);
    nameLb.textColor = UIColor.whiteColor;
    _nameLb = nameLb;
    [titleView addSubview:nameLb];
    
    UIImageView *arrowIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"arrow_down")];
    [titleView addSubview:arrowIcon];
    
    [nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(titleView);
        make.top.bottom.equalTo(titleView);
    }];
    [arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleView);
        make.width.mas_equalTo(12);
        make.height.mas_equalTo(12);
        make.left.equalTo(nameLb.mas_right).offset(5);
    }];
    
    [self zx_addCustomTitleView:titleView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleViewClick)];
    [titleView addGestureRecognizer:tap];
}

- (void)titleViewClick {
    [self.popUsersView showWithAnimated:YES];
}

#pragma mark - load data
- (void)getBindUserData {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEBindUserModel *ower = [HEBindUserModel new];
    ower.id = user.id;
    ower.realname = user.realname;
    ower.relations = @"本人";
    
    if (!_selectUser) {
        _selectUser = ower;
    }
    
    if (_bindUsers) {
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[UserManager sharedUserManager].curUserInfo.id forKey:@"gid"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetBindUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            weakSelf.bindUsers = @[].mutableCopy;
            [weakSelf.bindUsers addObject:ower];
            [weakSelf.bindUsers addObjectsFromArray:[HEBindUserModel mj_objectArrayWithKeyValuesArray:response.data]];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)initUI {
    
   _vcs = @[].mutableCopy;
    NSMutableArray *titles = @[].mutableCopy;

    for (HEDataManageModel *model in _dataSourceArr) {
        HEHealthCheckChartController *vc = [HEHealthCheckChartController new];
        vc.model = model;
        vc.selectUser = _selectUser;
        [_vcs addObject:vc];
        [titles addObject: model.check_name];
    }
    
    MJCSegmentStylesTools *tools = [MJCSegmentStylesTools jc_initWithSegmentStylestoolsBlock:^(MJCSegmentStylesTools *jc_tools) {
        jc_tools.
        jc_titleBarStyles(MJCTitlesScrollStyle).
        jc_titlesViewFrame(CGRectMake(0, ZXNavBarHeight, self.view.jc_width, 47)).
        jc_indicatorStyles(MJCIndicatorEqualTextEffect).
        jc_indicatorFrame(CGRectMake(0, 47-3, 0, 3)).
        jc_titlesViewBackColor(CNavBgColor).
        jc_itemTextSelectedColor(UIColorWhite).
        jc_itemTextNormalColor(KHexColor(@"c3d3ff")).
        jc_itemTextZoomEnabled(YES, 17).
        jc_itemTextFontSize(15).
        jc_defaultItemShowCount(5).
        jc_childsContainerBackColor(UIColorWhite).
        jc_indicatorColor(UIColorWhite).
        jc_indicatorHidden(NO).
        jc_indicatorsAnimalsEnabled(YES).
        jc_childScollEnabled(YES).
        jc_childScollAnimalEnabled(YES).
        jc_indicatorFollowEnabled(YES).
        jc_itemTextsEdgeInsets(UIEdgeInsetsMake(10,10,10,10)).
        jc_itemTextGradientEnabled(YES).
        jc_itemSelectedSegmentIndex(self->_index);
    }];
    
    MJCSegmentInterface *interFace = [MJCSegmentInterface initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) interFaceStyletools:tools];
    [self.view addSubview:interFace];
    [interFace intoTitlesArray:titles intoChildControllerArray:_vcs hostController:self];
    
    interFace.qmui_borderPosition = QMUIViewBorderPositionBottom;
    interFace.qmui_borderWidth = 1;
    interFace.qmui_borderColor = CSplitLineColor;
    [self zx_setPopGestureCompatibleScrollView: interFace.childMainView];
}


- (void)setupData {
  
    NSMutableArray *items = @[].mutableCopy;
    HEDataManageModel *ht = [HEDataManageModel new];
    ht.leftImage = @"home_tall";
    ht.check_name = @"身高";
    ht.check_code = @"Ht";
    ht.check_unit = @"cm";
    ht.normalRangs = @[@{@"name":@"身高", @"value":@"1.2-1.8米"}];
    
    HEDataManageModel *wt = [HEDataManageModel new];
    wt.leftImage = @"home_weight";
    wt.check_name = @"体重";
    wt.check_code = @"Wt";
    wt.check_unit = @"wt";
    wt.normalRangs = @[@{@"name":@"体重", @"value":@"40-70公斤"}];

    HEDataManageModel *bt = [HEDataManageModel new];
    bt.leftImage = @"home_temperature";
    bt.check_name = @"体温";
    bt.check_code = @"Bt";
    bt.check_unit = @"℃";
    bt.normalRangs = @[@{@"name":@"体温", @"value":@"36.4-37.4℃"}];

    HEDataManageModel *Hxcs = [HEDataManageModel new];
    Hxcs.leftImage = @"home_breathe";
    Hxcs.check_name = @"呼吸次数";
    Hxcs.check_code = @"Hxcs";
    Hxcs.check_unit = @"次/分";
    Hxcs.normalRangs = @[@{@"name":@"呼吸次数", @"value":@"16-25次/分"}];

    HEDataManageModel *H = [HEDataManageModel new];
    H.leftImage = @"home_sleep";
    H.check_name = @"睡眠";
    H.check_code = @"sleep";
    H.check_unit = @"H";
    H.normalRangs = @[@{@"name":@"睡眠", @"value":@"6-12小时"}];

    HEDataManageModel *xy = [HEDataManageModel new];
    xy.leftImage = @"home_blood_pressure";
    xy.check_name = @"血压";
    xy.check_code = @"xy";
    xy.check_unit = @"mmg";
    xy.normalRangs = @[@{@"name":@"收缩压", @"value":@"60-90mmgHg"},
                       @{@"name":@"舒张压", @"value":@"90-140mmgHg"}];

    HEDataManageModel *BS = [HEDataManageModel new];
    BS.leftImage = @"home_blood_glucose";
    BS.check_name = @"血糖";
    BS.check_code = @"BS";
    BS.check_unit = @"mmol/L";
    BS.normalRangs = @[@{@"name":@"血糖", @"value":@"4.0-6.1mmol/L"}];

    HEDataManageModel *SaO2 = [HEDataManageModel new];
    SaO2.leftImage = @"home_blood_o2";
    SaO2.check_name = @"血氧";
    SaO2.check_code = @"SaO2";
    SaO2.check_unit = @"%";
    SaO2.normalRangs = @[@{@"name":@"血氧", @"value":@"≥95%"}];

    HEDataManageModel *rhr = [HEDataManageModel new];
    rhr.leftImage = @"home_heart_rate";
    rhr.check_name = @"静息心率";
    rhr.check_code = @"rhr";
    rhr.check_unit = @"次/分";
    rhr.normalRangs = @[@{@"name":@"静息心率", @"value":@"60-100次/分"}];

    HEDataManageModel *BMI = [HEDataManageModel new];
    BMI.leftImage = @"home_bmi";
    BMI.check_name = @"BMI";
    BMI.check_code = @"bmi_name";
    BMI.check_unit = @"kg/㎡";
    BMI.normalRangs = @[@{@"name":@"BMI", @"value":@"18.5-25"}];

    
    if (_dataSourceArr.count == 0) {
        _dataSourceArr = @[ht, wt, bt, Hxcs, H, xy, BS, SaO2, rhr, BMI].mutableCopy;
    }
    
    items = @[ht, wt, bt, Hxcs, H, xy, BS, SaO2, rhr, BMI].mutableCopy;
    
    for (HEDataManageModel *item in items) {
        for (HEDataManageModel *model in _dataSourceArr) {
            if ([model.check_name isEqualToString: item.check_name]) {
                model.normalRangs = item.normalRangs;
                break;
            }
        }
    }
}

#pragma mark -
- (QMUIPopupMenuView *)popUsersView {
    if (!_popUsersView) {
         
        // 使用方法 2，以 UIWindow 的形式显示到界面上，这种无需默认隐藏，也无需 add 到某个 UIView 上
        _popUsersView = [[QMUIPopupMenuView alloc] init];
        _popUsersView.automaticallyHidesWhenUserTap = YES;// 点击空白地方消失浮层
        _popUsersView.itemTitleColor = CNavLightBlackColor;
        _popUsersView.maskViewBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];// 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
        _popUsersView.shouldShowItemSeparator = YES;
        _popUsersView.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
            // 利用 itemConfigurationHandler 批量设置所有 item 的样式
            aItem.button.highlightedBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];
        };
        KWeakSelf
        NSMutableArray *items = @[].mutableCopy;
        for (HEBindUserModel *model in self.bindUsers) {
            QMUIPopupMenuButtonItem *item = [QMUIPopupMenuButtonItem itemWithImage:nil title: [NSString stringWithFormat:@"%@（%@）",model.realname, model.relations] handler:^(QMUIPopupMenuButtonItem *aItem) {
                [aItem.menuView hideWithAnimated:YES completion:^(BOOL finished) {
                    weakSelf.nameLb.text = [NSString stringWithFormat:@"健康数据(%@)", model.realname];
                    weakSelf.selectUser = model;
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationSelectBindUser object:model];
                }];
            }];
            [items addObject:item];
        }
        
        _popUsersView.items = items;
        _popUsersView.didHideBlock = ^(BOOL hidesByUserTap) {
            
        };
        _popUsersView.sourceView = self.zx_navTitleView;// 相对于 button4 布局
    }
    return _popUsersView;
}


@end
